#include "tcpclient.h"

TCPClient::TCPClient(QObject *parent) : QObject(parent)
{
    m_tcpsocket = new QTcpSocket(this);

    m_bIsConnect = false;
    m_bDisconnect = false;
    m_bCloseOver = false;
    TcpSocketConnects();
}

///
/// \brief 初始化connect
///
void TCPClient::TcpSocketConnects()
{
    // 连接槽函数
    connect(m_tcpsocket, &QTcpSocket::connected,
            [=]()
            {
                m_bIsConnect = true;
                TcpSocketConnected();
                emit ConnectedSignal();
            });
    // 断开槽函数
    connect(m_tcpsocket, &QTcpSocket::disconnected,
            [=]()
            {
                if (m_bDisconnect == true)
                {
                    m_bDisconnect = false;
                }
                else
                {
                    Disconnected();
                }
                if (!m_bCloseOver)
                {
                    emit DisconnectedSignal();
                }
            });
}

///
/// \brief TcpSocket 连接成功
///
void TCPClient::TcpSocketConnected()
{
    // 读取数据槽函数
    connect(m_tcpsocket, &QTcpSocket::readyRead,
            [=]()
            {
                TcpSocketReadyRead();
            });
}

///
/// \brief TCPSocket 断开
///
void TCPClient::Disconnected()
{
    if (m_bDisconnect == false)   // 防止重复进入该函数
    {
        m_bDisconnect = true;
    }
    m_tcpsocket->disconnectFromHost();
    if (m_bIsConnect == false)
    {
        m_tcpsocket->waitForDisconnected(50);
    }
    else
    {
        m_bIsConnect = false;
    }
    m_tcpsocket->close();
    m_tcpsocket->deleteLater();
    m_tcpsocket = nullptr;
    m_tcpsocket = new QTcpSocket(this);
    TcpSocketConnects();
}

void TCPClient::SetCloseOver(bool closeover)
{
    m_bCloseOver = closeover;
}

///
/// \brief TcpSocket 读取数据
///
void TCPClient::TcpSocketReadyRead()
{
    QByteArray data = m_tcpsocket->readAll();
    //qDebug() << "TCP Client readdata:" << data;
    emit ReadDataSignal(data);
}

///
/// \brief TCPSocket 发送数据
/// \param writedata: 数据内容
///
void TCPClient::WriteData(QByteArray writedata)
{
    m_tcpsocket->write(writedata);
}

///
/// \brief 返回连接状态
/// \return
///
bool TCPClient::isOpen()
{
    return m_tcpsocket->isOpen();
}

bool TCPClient::isValid()
{
    return m_tcpsocket->isValid();
}

bool TCPClient::isConnect()
{
    return m_bIsConnect;
}

///
/// \brief 连接主机
/// \param ip
/// \param port
///
void TCPClient::Connect(QString ip, quint16 port)
{
    m_tcpsocket->connectToHost(ip, port);
    //m_nIsConnect = m_tcpsocket->waitForConnected(1000);
}
